<?php

namespace App\Http\Controllers\Api;

use App\Models\Order;
use App\Models\User;
use App\Pay\Money;
use EasyWeChat\Pay\Application;
use Illuminate\Http\Request;

class PayController extends ApiBaseController
{
    //余额支付
    public function  payMoney(Request $request)
    {
        $order_no = $request->input('sn');
        $amount   = $request->input('total');
        $order = Order::where('sn',$order_no)->first();
        $user = User::where('id',$order->user_id);
        if($order->total > $user->money) {
            return $this->errRes(-1,"余额不足");
        }
        (new Money())->handel($order,$user,$amount);
        return $this->sucRes(200);
    }
    //微信支付
    public function payWechat(Request $request)
    {
        $order_no = $request->input('sn');
        $amount   = $request->input('total');
        $order = Order::where('sn',$order_no)->first();
        $user = User::where('id',$order->user_id);

        $config = [
            'mch_id' => config('wechat_mch_id'),
            // v3 API 秘钥
            'secret_key' => config('wechat_secret_key'),
        ];
        $app = new Application($config);
        $utils = $app->getUtils();
        $appId = config('wechat_app_id');
        $signType = 'RSA'; // 默认RSA，v2要传MD5
        $config = $utils->buildMiniAppConfig($order->sn, $appId, $signType);

        return $this->sucRes(200,[
            'appid'=>$appId,
            'mchid'=>config('wechat_mch_id'),
            'description'=>'test',
            'amount'=>[
                'total'=>$amount,
                'currency'=>'CNY'
            ],
            'openid'=>$user->getWechatUser($user->id)->openid,
            'notify'=>config('website').'/notify/pay/wechat',
            'config'=>$config
        ]);
    }
}
